package com.zbl.zblproject.erp.entity;

import com.zbl.zblproject.core.mapper.AdminUserMapper;
import com.zbl.zblproject.core.mapper.OrderMapper;
import com.zbl.zblproject.core.mapper.SupplierMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/30
 */
public class ErpOweTableContainer {


    private List<ErpOweTable> tables;

    private OrderMapper orderMapper;

    private AdminUserMapper adminUserMapper;

    private SupplierMapper supplierMapper;

    public ErpOweTableContainer(OrderMapper orderMapper, AdminUserMapper adminUserMapper, SupplierMapper supllierMapper){
        tables = new ArrayList<>();
        this.orderMapper = orderMapper;
        this.adminUserMapper = adminUserMapper;
        this.supplierMapper = supllierMapper;
    }

    public boolean isEmpty(){
        return tables.isEmpty();
    }

    public List<ErpOweTable> getTables() {
        return tables;
    }

    public void setTables(List<ErpOweTable> tables) {
        this.tables = tables;
    }

    public void addErpOweItem(ErpOweGoodsItem item){
        //判断是否为用户订单
        ErpOweTable oweTable;
        if(item.getMode() == 0){
            //欠货
            oweTable = getTableBySupplier(item.getSupplierId());
        }else{
            //缺货
            oweTable = getTableByUser(item.getUserId());
        }
        if(oweTable == null){
            oweTable = new ErpOweTable();
            if(item.getMode() == 0){
                //厂家订单
                oweTable.setMode(0);
                oweTable.setSupplier(supplierMapper.selectById(item.getSupplierId()));
            }else{
                //用户订单
                oweTable.setMode(1);
                oweTable.setAdminUser(adminUserMapper.selectById(item.getUserId()));
            }
            oweTable.setItems(new ArrayList<>(20));
            tables.add(oweTable);
        }
        oweTable.getItems().add(item);
    }

    private  ErpOweTable getTableByUser(int userId){
        ErpOweTable erpOweTable =  tables.stream().filter(x->{
            return x.getAdminUser() != null && x.getAdminUser().getUserId() == userId;
        }).findFirst().orElse(null);
        return erpOweTable;
    }

    private ErpOweTable getTableBySupplier(int supplierId){
        ErpOweTable erpOweTable =  tables.stream().filter(x->{
            return x.getSupplier() != null && x.getSupplier().getSuppliersId()== supplierId;
        }).findFirst().orElse(null);
        return erpOweTable;
    }
}
